package com.baidu.networkdemo

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.baidu.networkdemo.api.Repository
import com.baidu.networkdemo.model.Data
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainViewModel: ViewModel() {
    private val repository = Repository()
    private var topIndex = 1
    private var lastIndex = 0

    val dataList = MutableLiveData<ArrayList<Data>>(arrayListOf())

    /*
     https://api.spoonacular.com/recipes/complexSearch?query=bread&diet=vegetarian&type=breakfast&instructionsRequired=true&fillIngredients=true&number=1&apiKey=1a0edebda73f4a17ad82375357e41313
     */
    fun onLoadMovies(){
        viewModelScope.launch(Dispatchers.IO){

            val response = repository.getMovies(lastIndex+1)
            if (response.isSuccessful) {
                response.body()?.let { movie ->
                    lastIndex += 1
                    val newData = dataList.value
                    newData?.addAll(movie.data)
                    dataList.postValue(newData!!)
                }
            }
        }
    }

    fun onRefreshMovies(){
        viewModelScope.launch(Dispatchers.IO){
            if (topIndex-1 >= 1) {
                val response = repository.getMovies(topIndex-1)
                if (response.isSuccessful) {
                    response.body()?.let { movie ->
                        dataList.value?.addAll(movie.data)
                        topIndex --
                    }
                }
            }
        }
    }
}